package qjc.j_回溯;

import java.util.ArrayList;
import java.util.List;

public class j7_分割回文串 {
    public List<List<String>> partition(String s) {
        List<List<String>> res = new ArrayList<List<String>>();
        List<String> output = new ArrayList<>();
        backtrack(res, output, s, 0);
        return res;
    }

    private void backtrack(List<List<String>> res, List<String> output, String s, int start) {
        if (start == s.length()) {
            res.add(new ArrayList<>(output));
        }
        for (int i = start + 1; i <= s.length(); i++) {
            String temp = s.substring(start, i);
            if(isValid(temp)){
                output.add(temp);
                backtrack(res, output, s, i);
                output.remove(output.size() - 1);
            }
        }
    }

    private boolean isValid(String s) {
        int left = 0;
        int right = s.length() - 1;
        while (left < right) {
            if (s.charAt(left) != s.charAt(right)) {
                return false;
            }
            left++;
            right--;
        }
        return true;
    }
}
